package com.nxcy.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtil {
    private final String DBDRIVER = "com.mysql.jdbc.Driver";
    private final String DBURL = "jdbc:mysql://39.100.107.40:3306/enrollmentwz_test";
    private final String DBUSER = "root";
    private final String PASSWORD = "bigsail5062168!";
    private static Connection connection = null;
    private Connection getConnection() throws Exception {
        Class.forName(DBDRIVER);
        if (connection != null && !connection.isClosed()) {
            return connection;
        } else {
            connection = DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
        }
        return connection;
    }

    public ResultSet query(String sql) throws Exception
    {
        getConnection();
        Statement statement = connection.createStatement();
        return statement.executeQuery(sql);
    }

    public List<Map<String, String>> query4list(String sql) throws Exception {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        getConnection();
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        //把rs中的所有记录全部取出来，然后装到你自己的list中去
        ResultSetMetaData rsm=rs.getMetaData();
        int columnSize=rsm.getColumnCount();
         while (rs.next())
         {
             Map<String,String> map=new HashMap<String, String>();
             for(int j=1;j<=columnSize;j++)
             {
                 map.put(rsm.getColumnName(j),rs.getString(j));
             }
             list.add(map);
         }
        return list;
    }

    public int update(String sql) throws Exception {
        getConnection();
        Statement statement = connection.createStatement();
        int num = statement.executeUpdate(sql);
        return num;

    }

    public  void close() throws Exception {
        if (connection != null) {
            connection.close();
            connection = null;
        }
    }
}
